package com.glela.controller;

import com.alibaba.fastjson.JSONObject;
import com.glela.api.im.util.CodeUtil;
import com.glela.api.im.util.IMConfig;
import com.glela.common.util.MD5Utils;
import com.glela.common.util.Sha1;
import com.glela.mq.service.OrderQueueService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.response.ResponseBaseModel;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/messageSync")
public class MessageSyncController extends LiveBaseController {

	private static Logger logger = LoggerFactory.getLogger(MessageSyncController.class);

	@Autowired
	private OrderQueueService orderQueueService;

	@RequestMapping("/notify")
	public ResponseEntity<?> notify(HttpServletRequest request) throws Exception {
		try {
			String signTimestamp = request.getParameter("signTimestamp");
			String nonce = request.getParameter("nonce");
			String signature = request.getParameter("signature");
			StringBuilder toSign = new StringBuilder(IMConfig.appSecret).append(nonce).append(signTimestamp);
			String sign = CodeUtil.hexSHA1(toSign.toString()).toLowerCase();
			if (!sign.equals(signature)) {
				throw new Exception();
			}
			String fromUserId = request.getParameter("fromUserId");
			String toUserId = request.getParameter("toUserId");
			String objectName = request.getParameter("objectName");
			String content = request.getParameter("content");
			String channelType = request.getParameter("channelType");
			String msgTimestamp = request.getParameter("msgTimestamp");
			String msgUID = request.getParameter("msgUID");
			String sensitiveType = request.getParameter("sensitiveType");
			String source = request.getParameter("source");
			JSONObject json = new JSONObject();
			json.put("fromUserId", fromUserId);
			json.put("toUserId", toUserId);
			json.put("objectName", objectName);
			json.put("content", content);
			json.put("channelType", channelType);
			json.put("msgUID", msgUID);
			json.put("sensitiveType", sensitiveType);
			json.put("source", source);
			json.put("msgTimestamp", msgTimestamp);
//			orderQueueService.messageSync(json);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
		} catch (Exception e) {
			logger.error("聊天室消息同步失败", e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}

	/*
	 * @RequestMapping("/send") public String send(){ JSONObject json = new
	 * JSONObject(); json.put("fromUserId","12321"); try {
	 * orderQueueService.messageSync(json); } catch (Exception e) {
	 * e.printStackTrace(); } return "ok"; }
	 */
}
